# -*- coding: utf-8 -*-
import re
from datetime import datetime, timedelta
from metlib.shell.fileutil import *
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, \
    HttpResponseNotFound, Http404, \
    HttpResponseServerError, HttpResponseNotAllowed, \
    HttpResponseBadRequest
from metlib.misc.datatype import Null
from metlib.misc.misc import gen_uuid8, parse_bool
from weblib.django.http.response import *
from weblib.django.setting import get_setting
from .data_utils import *
from datasets.dataset_molds.FG_WRF_S3.fg_wrf_common import fgwrf_zh_varname_d, fgwrf_zh_subset_d, fgwrf_units_d, \
    fgwrf_pt_suggest_range_d


def get_station_info(request, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        range = info["range"]
        info["platform"] = info.pop("platform", None)
        info["data_count"] = info.pop("count", 0)
        platform = info["platform"]
        data_count = int(info["data_count"])
        result_dict = []
        if range == "china":
            datas = MapPointData.get_china_station_data(platform)
            for data in datas:
                if data.data_count > data_count:
                    chinadata = {}
                    chinadata["station_id"] = data.station_id
                    chinadata["platform"] = data.platform
                    chinadata["longitude"] = data.longitude
                    chinadata["latitude"] = data.latitude
                    chinadata["station_name"] = data.station_name
                    chinadata["frist_data_time"] = data.frist_data_time.strftime("%Y-%m-%d %H:%M:%S")
                    chinadata["last_data_time"] = data.last_data_time.strftime("%Y-%m-%d %H:%M:%S")
                    chinadata["data_count"] = int(data.data_count)
                    result_dict.append(chinadata)


        elif range == "global":
            pass
            # data = MapPointData.get_china_original_data()
        response = HttpResponse(json.dumps(result_dict), content_type="text/plain")
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "*"

        return response
        # return JsonResponse(result_dict)
    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/chart/?lat=XX&lon=XX&betdt=1990010100enddt=1990010100" 级别一-
# 无可用数据时的http response.
def get_station_data(request, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        info["begdt"] = datetime.strptime(info["begdt"], "%Y%m%d%H")
        info["enddt"] = datetime.strptime(info["enddt"], "%Y%m%d%H")
        begdt = info["begdt"].strftime("%Y-%m-%d %H:%M:%S")
        enddt = info["enddt"].strftime("%Y-%m-%d %H:%M:%S")
        station_id = info["station_id"]
        pt_datas = MapLitterData.get_point_for_stationid(station_id, begdt, enddt)
        key_convert_dict = {
            'dew': 'tdew',
            'dir': 'wdir',
            'temp': 't'
        }
        data_dict = {}
        data_dict["data"] = []
        for data in pt_datas:
            level_info = json.loads(data.level_info)
            for level_data in level_info:
                date_char = data.date_char.strftime("%Y-%m-%d %H:%M:%S")
                type = False
                for i in data_dict["data"]:
                    if i.has_key("level") and i["level"] == level_data["level"]:
                        type = True
                        break
                if type == True:
                    for i in data_dict["data"]:
                        i["dtime"].append(date_char)
                        if i.has_key("level") and i["level"] == level_data["level"]:
                            for k, v in level_data.items():
                                if v == "" or v == -888888.0 or v == 999999.0 or v == -888888 or v == -999999:
                                    v = None
                                if v is not None:
                                    if k == 'temp' or k == 'dew':
                                        v = v - 273.15
                                    if k == 'pres':
                                        v = v / 100
                                if k in key_convert_dict:
                                    nk = key_convert_dict[k]
                                else:
                                    nk = k
                                if k != "level" and i.has_key(nk) and k != "little_data_id":
                                    i[nk].append(v)

                else:
                    level_data_json = {}
                    level_data_json["dtime"] = []
                    level_data_json["dtime"].append(date_char)
                    for k, v in level_data.items():
                        if v == "" or v == -888888.0 or v == 999999.0 or v == -888888 or v == -999999:
                            v = None
                        if v is not None:
                            if k == 'temp' or k == 'dew':
                                v = v - 273.15
                            if k == 'pres':
                                v = v / 10000
                        if k != "level" and k != "little_data_id":
                            if k in key_convert_dict:
                                nk = key_convert_dict[k]
                            else:
                                nk = k
                            level_data_json[nk] = []
                            level_data_json[nk].append(v)
                        elif k == "level":
                            level_data_json["level"] = v
                    data_dict["data"].append(level_data_json)
        response = JsonResponse(data_dict)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "*"
        return response

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)
